import configparser
from pymongo import MongoClient
from pathlib import Path
import os
import utils.mylogger as log

myLogger = log.Mylogger()

config_parser =  configparser.ConfigParser()
config_file = os.path.join(Path(__file__).resolve().parent,"mongodb.cfg")
config_parser.read(config_file)

# db connectin config
DB_IP = config_parser.get("connection","ip")
DB_PORT = config_parser.get("connection","port")
USER_NAME = config_parser.get("connection","user_name")
PASSWORD = config_parser.get("connection","password")

# db tables config
DB_NAME = config_parser.get("dbconfig","db_name")
COLLECTION_NAME = config_parser.get("dbconfig","collection_name")



class Mongo(object):
    
    def __init__(self, db_name=DB_NAME):
        self.db_name = db_name
        try:
            self.client = MongoClient(host=DB_IP,port=int(DB_PORT),username=USER_NAME,password=PASSWORD)
        except Exception as e:
            myLogger.debug("Exception: {}".format(e))
        else:   
            print('---------- 数据库已连接 ---------------')
            self.db = self.client[self.db_name]

    def __enter__(self):
        return  self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('关闭数据库连接')
        self.client.close()
    
    def hello(self):
    	print('hello')

    def addOne(self,data:map, collection_name :str = DB_NAME) -> bool:
        try:
            self.db[collection_name].insert_one(data)
        except Exception as e:
            myLogger.debug("Exception: {}".format(e))
            return False
        else:
            return True

    def addMany(self,data:[map], collection_name :str = DB_NAME) -> bool:
        try:
            self.db[collection_name].insert_many(data)
        except Exception as e:
            myLogger.debug("Exception: {}".format(e))
            return False
        else:
            return True
